package com.weasel.weixin.commons.media;

import com.weasel.http.SimpleHttpUploadAndDownloadSecretary;
import com.weasel.http.handler.DownloadHandler;
import com.weasel.http.handler.UploadHandler;
import com.weasel.http.helper.HttpResponseHelper;
import com.weasel.http.helper.HttpUrlHelper;
import com.weasel.weixin.commons.CommonRequest;
import com.weasel.weixin.commons.config.CommonConfig;
import com.weasel.weixin.commons.media.bean.Media;
import org.apache.commons.io.FileUtils;
import org.apache.http.client.methods.CloseableHttpResponse;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;

/**临时素材请求类
 * Created by Dylan on 2015/9/29.
 */
public abstract class MediaRequest extends CommonRequest {


    public MediaRequest(CommonConfig config) {
        super(config);
    }


    public MediaResponse upload(Media media) throws ExecutionException, IOException {

        String uri = HttpUrlHelper.withURL(getUploadURI()).addParam("access_token",getAccessToken()).addParam("type",media.getType()).build();;

        return SimpleHttpUploadAndDownloadSecretary.upload(uri, new File[]{media.getFile()},new UploadHandler<MediaResponse>() {
                @Override
                public MediaResponse handler(CloseableHttpResponse response) {

                    try {
                        return HttpResponseHelper.jsonResponseToEntity(response, MediaResponse.class);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            });
    }

    public MediaResponse download(String mediaId,String fileDirectory) throws ExecutionException, IOException {

        String uri = HttpUrlHelper.withURL(getDownloadURI()).addParam("access_token",getAccessToken()).addParam("media_id",mediaId).build() ;
        return SimpleHttpUploadAndDownloadSecretary.download(uri, new DownloadHandler<MediaResponse>() {
            @Override
            public MediaResponse handler(CloseableHttpResponse response, InputStream fileInputStream) {

                MediaResponse mediaResponse = null;
                try {
                   //  mediaResponse = HttpResponseHelper.jsonResponseToEntity(response, MediaResponse.class);
                     FileUtils.copyInputStreamToFile(fileInputStream, new File(fileDirectory+getFileName(response)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return mediaResponse;
            }
        });
    }

    protected abstract String getUploadURI();

    protected abstract String getDownloadURI();

}
